<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="searchItemCount"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="projectEnv" label="环境">
          <!-- <FISelect
            v-model="state.query.projectEnv"
            valueCustom="value"
            :codeOption="{ codesetCode: 'iplat.ed.projectEnv' }"
            v-model:key-word="keyWord"
            clearable
          /> -->
          <FISelect v-model="state.query.projectEnv" valueCustom="value" :options="envArray" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="project" label="后端项目名">
          <FISelect
            v-if="arr2.length > 0"
            v-model="state.query.project"
            valueCustom="value"
            :options="arr2"
            clearable
          />
        </FIFormItem>
      </el-col>

      <!-- <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="projectEname" label="前端项目">
            <FIInput v-model="state.query.projectEname" clearable />
          </FIFormItem>
        </el-col> -->

      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="moduleEname1" label="一级模块">
          <FIInput v-model="state.query.moduleEname1" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="moduleEname2" label="二级模块">
          <FIInput v-model="state.query.moduleEname2" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="configEnvCname" label="配置环境名称">
          <FIInput v-model="state.query.configEnvCname" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="环境配置管理列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="configEnvId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      deletable
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @row-add="onAddRow"
      @row-delete="deleteRow"
    >
      <template #headerBtn>
        <!-- <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ id: 'delete', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn> -->
      </template>

      <template #project="{ scope }">
        <FISelect
          @change="onCellChange($event, scope.$index)"
          v-if="scope.row.isSelected"
          v-model="scope.row.project"
          valueCustom="value"
          :options="arr2"
          clearable
        />
        <span v-else>{{ scope.row.project }}</span>
      </template>

      <template #moduleEname1="{ scope }">
        <!-- {{scope.row.moduleEname1Options}} -->

        <FISelect
          v-if="scope.row.isSelected"
          @focus="onfocusEvent($event, scope.$index)"
          @change="handleChange($event, scope.$index)"
          v-model="scope.row.moduleEname1"
          valueCustom="value"
          :options="scope.row.moduleEname1Options"
          clearable
        />
        <!-- <el-select
            v-if="scope.row.isSelected"
    v-model="scope.row.moduleEname1"
    :empty-values="[null, undefined]"
    :value-on-clear="null"
    clearable
    placeholder="Select"
    style="width: 240px"
    @change="handleChange"
   
  >
    <el-option
      v-for="item in scope.row.moduleEname1Options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select> -->
        <span v-else>{{ scope.row.moduleEname1 }} </span>
      </template>

      <template #moduleEname2="{ scope }">
        <!-- {{ scope.row.moduleEname2 }} -->
        <!-- {{scope.row.moduleEname1Options}} -->

        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.moduleEname2"
          valueCustom="value"
          :options="scope.row.moduleEname2ptions"
          clearable
        />
        <!-- <el-select
            v-if="scope.row.isSelected"
    v-model="scope.row.moduleEname2"
    :empty-values="[null, undefined]"
    :value-on-clear="null"
    clearable
    placeholder="Select"
    style="width: 240px"
   
  >
    <el-option
      v-for="item in scope.row.moduleEname2ptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select> -->
        <span v-else>{{ scope.row.moduleEname2 }} </span>
      </template>
      <template #projectEnv="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.projectEnv"
          valueCustom="value"
          :options="envArray"
          clearable
        />
        <span v-else>{{ envTextFunc(scope.row.projectEnv) }}</span>
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, nextTick } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { apiGetModule1, apiGetbackproject, apiGetModule2, apiGetenv } from '@/api/configEnvMaint/index.ts'

import LocalCache from '@/utils/cache'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiQueryCodeitem } from '@/api/common'
import { da } from 'element-plus/es/locale'

const route = useRoute()

const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'pageMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const arr1 = ref([])
const envArray = ref([
  {
    value: 'DEV',
    label: '开发环境',
  },
  {
    value: 'TEST',
    label: '测试环境',
  },
  {
    value: 'RUN',
    label: '生产环境',
  },
])
const state = reactive({
  query: {
    projectEnv: '',
    project: '',
    moduleEname1: '',
    moduleEname2: '',
    configEnvCname: '',

    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  // {
  //   label: '环境ID',
  //   prop: 'configEnvId',
  //   align: 'center',
  //   width: '120',
  //   // editable: false,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '配置环境名称',
    prop: 'configEnvCname',
    queryName: 'tedfa00.form_Cname',
    align: 'center',

    editType: 'input',
    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { configEnvCname: [{ required: true, message: '请输入配置环境名称', trigger: 'blur' }] },
    },
  },

  {
    label: '后端项目名',
    prop: 'project',
    queryName: 'tedfa00.form_Cname',
    align: 'center',

    editType: 'input',
    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    // modelValue: { inputValue: '', isBlank: false, notBlank: false },
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { project: [{ required: true, message: '请输入后端项目名', trigger: 'blur' }] },
    },
  },
  //   {
  //   label: '一级模块',
  //   prop: 'moduleEname1',
  //   align: 'center',
  //   width: '130',
  //   editable: true,
  //   filterable: true,
  //   sortable: true,
  //   editType: 'select',
  //   modelValue: [],
  //   configValueToLable: {
  //     list: [
  //       { value: '1', label: '是' },
  //       { value: '0', label: '否' },
  //     ],
  //   },
  //   editConfig: {
  //     rules: { isAuth: [{ required: true, message: '请输入是否授权', trigger: 'blur' }] },
  //     // options: [
  //     //   { 'value': '1', 'label': '是1',},
  //     //   { 'value': '0', 'label': '否' },
  //     // ],
  //   // options:[ { "label": "【csyjmk】去切作调严劳面", "value": "csyjmk" } ],
  //   options:arr1,
  //     selectBinds: {
  //       multiple: false,
  //       valueCustom: 'value',
  //     },
  //   },
  // },
  {
    label: '一级模块名',
    prop: 'moduleEname1',
    align: 'center',

    editable: true,
    // filterable: true,
    // sortable: true,
    required: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editConfig: {
      rules: { moduleEname1: [{ required: true, message: '请输入所属一级模块', trigger: 'blur' }] },
    },
  },
  {
    label: '二级模块名',
    prop: 'moduleEname2',
    align: 'center',

    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editConfig: {
      rules: { moduleEname2: [{ required: true, message: '请输入所属一级模块', trigger: 'blur' }] },
    },
  },
  {
    label: '环境',
    prop: 'projectEnv',
    align: 'center',
    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'select',
    editConfig: {
      options: [
        {
          value: 'DEV',
          label: '开发环境',
        },
        {
          value: 'TEST',
          label: '测试环境',
        },
        {
          value: 'RUN',
          label: '生产环境',
        },
      ],
    },
  },

  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])
const envTextFunc = (type) => {
  if (type == 'DEV') {
    return '开发环境'
  } else if (type == 'TEST') {
    return '测试环境'
  } else if (type == 'RUN') {
    return '生产环境'
  }
}
const arr2 = ref([])
const checkedRows = ref([])
const onAddRow = () => {
  console.log(tableRef.value.cloneTableData)
  //   // 找到选定的行并更新其 moduleEname1 选项
  //   const selectedRow = tableRef.value.cloneTableData.find((row) => row.project === e)

  // if (selectedRow) {
  //   selectedRow.moduleEname1Options = [
  //     {
  //       label: 'GLOBAL',
  //       value: 'GLOBAL',
  //     }
  //   ]
  // }
}
const handleSelectionChange = (e) => {
  checkedRows.value = e
  //   state.dataList = state.dataList.map((item) => ({
  //   ...item,
  //   moduleEname1Options:arr1, // 添加新属性
  // }));
  // let ids = ''
  // Array.isArray(checkedRows.value) &&
  //   checkedRows.value.forEach((item: any) => {
  //     if (item?.project)
  //     ids=item?.project
  //   })
  //   let data={
  //   projectEname:ids
  // }
  // apiGetModule1(data).then((res) => {
  // })
}
const onfocusEvent = (e, index) => {
  getModuleData(tableRef.value.cloneTableData[index].project, index)
}
const onCellChange = (e, index) => {
  // state.query.moduleEname = ''
  getModuleData(e, index)
  tableRef.value.cloneTableData[index].moduleEname1 = ''
  tableRef.value.cloneTableData[index].moduleEname2 = ''
}
const getModuleData = (e, index) => {
  // if (c.column.property === 'moduleEname1') {
  if (e) {
    apiGetModule1({ projectEname: e }).then((res) => {
      if (res.data.success) {
        Array.isArray(res.data.data) &&
          res.data.data.forEach((item) => {
            // state.dataList.forEach((item1,index)=>{

            // })
            // item.label = item.moduleCname2
            item.label = `[${item.moduleEname1}] ${item.moduleCname1}`
            item.value = item.moduleEname1
          })

        if (Array.isArray(res.data.data)) {
          const newArray = res.data.data.map((item) => ({
            label: `[${item.moduleEname1}] ${item.moduleCname1}`,
            value: item.moduleEname1,
          }))
          // 找到选定的行并更新其 moduleEname1 选项
          const selectedRow = tableRef.value.cloneTableData[index]
          // const selectedRow = tableRef.value.cloneTableData.find((row) => row.moduleEname1 === e)
          let obj = {
            label: 'GLOBAL',
            value: 'GLOBAL',
          }
          newArray.unshift(obj)
          if (selectedRow) {
            nextTick(() => {
              selectedRow.moduleEname1Options = newArray
            })
          }
          console.log(selectedRow, 'selectedRow.moduleEname1Options')

          //  arr1.value=newArray
          // state.dataList = state.dataList.map((item) => ({
          //   ...item,
          //   moduleEname1Options:newArray , // 添加新属性
          // }));
          // const selectedRowIndex = state.dataList.findIndex((row) => row.project === e);
          //   if (selectedRowIndex !== -1) {
          //     arr1.value[selectedRowIndex] = newArray;
          //   }

          // arr1.value=newArray
          // state.dataList
          nextTick(() => {
            // arr1.value=newArray
          })
        }
      }
    })
    // 如果是下拉框字段，触发接口获取选项
    //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
  }
}

// const onCellChange = (e,index) => {

// }
const handleChange = (e, index) => {
  console.log(e, tableRef.value.cloneTableData)
  tableRef.value.cloneTableData[index].moduleEname2 = ''
  apiGetModule2({ moduleEname1: e }).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          item.label = `[${item.moduleEname2}] ${item.moduleCname2}`
          item.value = item.moduleEname2
        })

      if (Array.isArray(res.data.data) && res.data.data.length) {
        const newArray = res.data.data.map((item) => ({
          label: `[${item.moduleEname2}] ${item.moduleCname2}`,
          value: item.moduleEname2,
        }))
        // 找到选定的行并更新其 moduleEname1 选项
        const selectedRow = tableRef.value.cloneTableData[index]
        let obj = {
          label: 'GLOBAL',
          value: 'GLOBAL',
        }
        newArray.unshift(obj)
        if (selectedRow) {
          selectedRow.moduleEname2ptions = newArray
        }
      } else {
        const selectedRow = tableRef.value.cloneTableData[index]
        selectedRow.moduleEname2ptions = [
          {
            label: 'GLOBAL',
            value: 'GLOBAL',
          },
        ]
      }
    }
  })
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiRequestPost('/rm2/configEnvMaint/query', state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/configEnvMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.configEnvId) ids.push(item?.configEnvId)
    })
  isTableLoading.value = true
  apiRequestPost('/rm2/configEnvMaint/delete', ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
const getProjectname = () => {
  apiGetbackproject().then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `[${item.projectEname}] ${item.projectCname}`
          item.value = item.projectEname
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `[${item.projectEname}] ${item.projectCname}`,
          value: item.projectEname,
        }))
        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr2.value = newArray
      }
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
const arr3 = ref([])
const getProjectenv = () => {
  apiQueryCodeitem({ codesetCode: 'iplat.ed.projectEnv' }).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `[${item.itemCode}] ${item.itemCname}`
          item.value = item.itemCode
        })
      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `[${item.itemCode}] ${item.itemCname}`,
          value: item.itemCode,
        }))
        arr3.value = newArray
      }
    }
  })
}
const arrEnv = ref([])
const getEnv = () => {
  let data = {
    size: 100,
  }
  apiGetenv(data).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data.result) &&
        res.data.data.result.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = item.configEnvCname
          item.value = item.configEnvId
        })

      if (Array.isArray(res.data.data.result)) {
        const newArray = res.data.data.result.map((item) => ({
          label: item.configEnvCname,
          value: item.configEnvId,
        }))
        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arrEnv.value = newArray
      }
      console.log(arrEnv, 'arrEnv123')
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
onMounted(() => {
  getProjectname()
  getEnv()
  getProjectenv()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
